<template>
	<view class="h-full">
		<uv-skeleton rows="10" :loading="firstLoading" rowsHeight="30px" title>
			<view class="space-between column h-full absolute" v-if="list">
				<view class="column p-10 g-10 ova">
					<view>
						<view class="h-65" :class="{ 'disable': list.status != 1 }">
							<view class="card p-0 h-fill column g-4 active" @click="chooseAddress"
								v-if="type.index == 0">
								<view v-if="isEmptyObject(address)">
									<view class="space-between align-center relative f-14 p-10">
										<view>选择地址</view>
										<view class="align-center bold">
											请选择地址
											<uv-icon name="arrow-right"></uv-icon>
										</view>
									</view>
								</view>
								<template v-else>
									<view class="align-center space-between relative f-16 bold">
										<view>
											{{ address.userName }}
											<span style="margin-left: 10px;">
												{{ address.telNumber }}
											</span>
										</view>
										<uv-icon v-if="list.status == 1" name="arrow-right"></uv-icon>
									</view>
									<view style="font-size: 12px;color: #666;">
										{{ address.addressDetail }}
									</view>
								</template>
							</view>
							<view class="card p-0 h-fill column g-4 active" @click="toMapList" v-else>
								<view v-if="isEmptyObject(selfAddress)">
									<view class="space-between align-center relative f-14 p-10">
										<view>选择自提门店</view>
										<view class="align-center bold">
											请选择自提门店
											<uv-icon name="arrow-right"></uv-icon>
										</view>
									</view>
								</view>
								<template v-else>
									<view class="align-center space-between relative f-16 bold">
										<view>
											{{ selfAddress.userName }}
											<span style="margin-left: 10px;">
												{{ selfAddress.telNumber }}
											</span>
										</view>
										<uv-icon v-if="list.status == 1" name="arrow-right"></uv-icon>
									</view>
									<view style="font-size: 12px;color: #666;">
										{{ selfAddress.addressDetail }}
									</view>
								</template>
							</view>
						</view>
					</view>
					<view class="card g-10">
						<view class="space-between size">
							<span style="display: flex;">订单编号：
								<uv-tooltip :text="list.order_no" :copyText="list.order_no" overlay color="red"
									bgColor="#e3e4e6" />
							</span>
							<span class="status">{{ list.status_text }}</span>
						</view>
						<view class="column g-10">
							<view class="center g-10 h-80 line">
								<view class="left">
									<img :src="list.items?.goods_cover" class="wh-full border" />
								</view>
								<view class="right column">
									<view class="weight fontLong">
										{{ list.items?.goods_name }}
									</view>
									<view class="size fontLong">
										{{ list.items?.goods_spec_show }}
									</view>
								</view>
							</view>
							<view v-if="!app.globalData.type" class="column g-10">
								<!-- <uv-line></uv-line> -->
								<view class="space-between">
									<view v-for="(item, index) in dateTime" class="flex center">
										<uv-avatar :text="index == 1 ? '还' : '始'" size="35" bg-color="#f5f5f5"
											:color="app.globalData.primaryColor"></uv-avatar>
										<view>
											<view style="font-size: 14px;
									color: #3b4144;">{{ item.title }}</view>
											<view style="color: #999;
									font-size: 12px;">{{ item.description }}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="cardBox" v-if="app.globalData.type">
						<view class="cardTitle">| 订单信息</view>
						<view class="card p-2">
							<uv-list>
								<uv-list-item title="下单时间" :right-text="list.create_at"></uv-list-item>
								<template v-for="(item, index) in list.leaseinfo" :key="index">
									<uv-list-item v-if="item.key != '选择优惠券'" :title="item.key"
										:right-text="item.value"></uv-list-item>
								</template>
							</uv-list>
						</view>
					</view>
					<view v-else class="column g-10">
						<view class="cardBox">
							<view class="cardTitle">| 租金详情
								<view class="cardExtra">租{{ list.expect * 30 }}天 | {{ list.expect }}期</view>
							</view>
							<view class="card p-2">
								<uv-list>
									<template v-for="(item, index) in list.leaseinfo" :key="index">
										<uv-list-item v-if="item.key != '选择优惠券'" :title="item.key"
											:right-text="item.value"></uv-list-item>
									</template>
								</uv-list>
							</view>
						</view>
						<view class="cardBox" v-if="list.status==4||list.status==5||list.status==6||list.status==7">
							<view class="cardTitle">| 每期租金情况
								<view class="cardExtra wobble-hor-bottom">
									点击期数可提前还款
								</view>
							</view>
							<view class="card p-10 pd-0 zujin">
								<uv-list>
									<template v-for="(item, index) in list.term_info" :key="index">
										<uv-list-item v-if="item.key"
											:title="item.key + ' (' + item.month + ') ' + term_status[item.status]"
											:right-text="item.value" @click="payMonthPay(item)"
											:customStyle="customStyle(item.status)"
											:show-arrow="item.status !== 1 && item.status !== 3"
											:clickable="item.status !== 1 && item.status !== 3"></uv-list-item>
									</template>
								</uv-list>
							</view>
						</view>
					</view>
					<view class="cardBox" v-if="list.status==2">
						<view class="cardTitle">| 订单备注</view>
						<uv-textarea v-model="remark" count maxlength="50" autoHeight placeholder="备注"
							border="none"></uv-textarea>
					</view>
					<view class="card g-10">
						<view class="cardTitle">遇到问题?</view>
						<view class="space-around">
							<view class="center active f-15" @click="callPhone">
								<uv-icon name="phone" :color="app.globalData.primaryColor" size="30"></uv-icon>
								客服热线
							</view>
							<!-- <view class="center active f-15"></view> -->
							<view class="center active f-15" @click="toComplain">
								<uv-icon name="email" :color="app.globalData.primaryColor" size="30"></uv-icon>
								投诉订单
							</view>
						</view>
					</view>
				</view>
				<view class="bottom" v-if="list.status != 0">

					<!-- <view class="testPay" @tap="onTestPay(1)">
						测试支付按钮
					</view> -->

					<view v-if="list.status == 1" class="center" style="font-size: small;">
						<uv-checkbox-group v-model="checked" shape="circle" @change="onChange">
							<uv-checkbox label="我已阅读并同意签署" :name="true" activeColor="red"></uv-checkbox>
						</uv-checkbox-group>
						<text style="color:#479de2" @click="onProtocol">(租赁服务协议及相关的内容)</text>
					</view>
					<uv-button v-if="list.status == 1" text="确认订单" @click="confirmOrder" :loading="loading" type="error"
						shape="circle" :color="app.globalData.primaryColor"></uv-button>
					<uv-button v-else-if="!is_realperson" text="去实名" @click="toRealperson" shape="circle"
						:color="app.globalData.primaryColor"></uv-button>
				</view>
				<!-- <nut-toast ref="toastRef" /> -->
				<uv-toast ref="toastRef"></uv-toast>
			</view>

			<view v-else>
				<view class="center wh-full absolute">
					<uv-empty mode="order"></uv-empty>
				</view>
			</view>
		</uv-skeleton>

		<h5pay ref="h5payRef" @showPreview="showPreview" />
	</view>
</template>

<script setup>
	//全部""，待下单1，待审核9，待签署 3，待发货 4，待收货6  5，租用中7，归还中8，已完成9 6，已取消0，已逾期is_timeout= 1
	import {
		ref,
		reactive,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad,
		onShow,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import useAdressList from '@/pages/addressList/addressListMetheds'
	import h5pay from '../../components/h5pay/h5pay';
	import config from '@/utils/config.js';
	const baseUrl = config.baseUrl
	const selfAddress = ref({})
	const term_status = ['待支付', '已支付', '待支付', '', '待支付', '已退款']
	const order_no = ref(null);
	const is_realperson = ref(null)
	const type = reactive({
		current: 0,
		index: 0,
		change(index) {
			app.vibrate()
			type.current = index;
			type.index = index;
		}
	})
	onLoad((e) => {
		if (!e?.order_no) {
			uni.switchTab({
				url: '/pages/index/index',
			})
			return
		}
		order_no.value = e.order_no

	})

	onPullDownRefresh((e) => {
		app.vibrate()
		uni.pageScrollTo({
			scrollTop: 0
		})
		getData(order_no.value)
		checkUser()
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 300)
	})

	onShow(() => {
		uni.pageScrollTo({
			scrollTop: 0
		})
		getData(order_no.value)
		checkUser()
	})
	const h5payRef = ref(null)

	const showPreview = (expact, price) => {
		h5payRef.value.open(expact, price, order_no.value)
	}
	const onTestPay = (expact) => {
		let req = {
			order_no: order_no.value,
			expact: expact
		}

		let provider = null
		uni.getProvider({
			service: 'payment',
			success: res => {
				provider = res.provider[0]
			},
			fail: res => {}
		})

		app.post('api.auth.order/payMonthPays', req).then(res => {
			uni.requestPayment({
				provider: provider,
				timeStamp: res.timeStamp + '',
				nonceStr: res.nonceStr,
				package: res.package,
				signType: 'MD5',
				paySign: res.paySign,
				success: () => {
					getData(order_no.value)
				},
				fail: (res) => {
					console.log(res)
					showToast('用户已取消支付')
				}
			})
		})
	}
	const {
		proxy
	} = getCurrentInstance()
	const app = getApp()
	const firstLoading = ref(false)
	const loading = ref(false)
	const list = ref({})
	const miniprogram_info = ref({})
	const remark = ref("")
	const {
		address,
		chooseAddress,
		setAddress
	} = useAdressList()
	const getData = (order_no) => {
		firstLoading.value = true
		app.get('api.auth.order/getOrdersFind', {
			order_no
		}).then(res => {
			list.value = res.list
			remark.value = res.list.remark
			if (res.list.send_type) {
				const send_type = parseInt(res.list.send_type) - 1
				type.list = [type.list[send_type]]
				type.current = 0
				type.index = send_type
				send_type == 1 ? setSelfAddress(res.storeInfo) : setAddress(res.list.address);
			} else if (res.list?.address?.type == 1) {
				setAddress(res.list.address)
			}
			miniprogram_info.value = res.miniprogram_info
			getTimes(res.list.sign_datetime, res.list.expect);
			firstLoading.value = false
		}).catch(error => {
			firstLoading.value = false
			list.value = null
			console.log(error);
		})
	}
	const checked = ref([])
	const onChange = (value) => {
		app.vibrate()
		console.log(value, '000000')
		checked.value = value
	}
	const onProtocol = () => {
		app.downloadFile("https://cdn.hangjizj.com/df/b1a64702c8578ebdbafa9271fc1baa.pdf")
	}
	const toastRef = ref(null)
	const showToast = (message, type = 'default') => {
		toastRef.value?.show({
			type,
			message
		})
	}
	const confirmOrder = () => {
		const eventChannel = proxy.getOpenerEventChannel();
		app.vibrate()
		if (type.current == 0 && !address.value?.code) {
			showToast('请选择配送地址')
			return
		}
		if (!checked.value[0]) {
			showToast('请勾选租赁服务协议')
			return
		}
		loading.value = true
		app.post('api.auth.order/perfect', {
			code: address.value.code,
			order_no: list.value.order_no,
			send_type: (type.current + 1),
			send_store_id: ((type.current + 1) == 2) ? selfAddress.value.id : null,
			remark: remark.value || ""
		}).then(res => {
			eventChannel.emit('close');
			// checkUser()
			toResults(res.order_no)
			// uni.hideLoading()
		}).catch(() => {
			loading.value = false
		})
	}
	const checkUser = () => {
		app.post('api.auth.center/isRealPerson').then(res => {
			is_realperson.value = res.is_realperson
		})
	}
	//下单成功页面
	const toResults = (order_no) => {
		uni.redirectTo({
			url: '/pages/results/results?order_no=' + order_no,
		})
	}
	//认证页面
	const toRealperson = () => {
		uni.navigateTo({
			url: '/pages/realperson/realperson?order_no=' + order_no.value,
		})
	}
	const isEmptyObject = (obj) => {
		return Object.keys(obj)?.length === 0;
	}
	const toDetail = () => {
		app.vibrate()
		uni.navigateTo({
			url: '/pages/goodsDetail/goodsDetail?code=' + list.value.order_no,
		})
	}
	const toComplain = () => {
		app.vibrate()
		const data = {
			order_no: list.value.order_no,
			store_id: list.value.store_id
		}
		uni.navigateTo({
			url: '/pages/complain/complain' + uni.$uv.queryParams(data)
		})
	}
	const toMapList = () => {
		uni.navigateTo({
			url: '/pages/mapList/mapList',
			events: {
				setAddress: setSelfAddress
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	}
	const setSelfAddress = (value) => {
		if (value) {
			selfAddress.value = {
				userName: value.company_name,
				telNumber: value.company_phone,
				addressDetail: value.company_address,
				...value,
			}
		}
	}
	const dateTime = ref([])
	const getTimes = (time, month) => {
		// 定义一个常量，表示3天的毫秒数
		const THREE_DAYS_MS = 3 * 24 * 60 * 60 * 1000;
		const setime = (timestamp, months) => {
			timestamp += THREE_DAYS_MS;
			var date = new Date(timestamp); // 转为Date对象
			date.setMonth(date.getMonth() + months); // 加上n个月
			var result = date.getTime(); // 转回时间戳
			dateTime.value = [{
					title: '预计起租日',
					icon: '/image/orderDetail/begin.png',
					description: uni.$uv.date(timestamp, 'yyyy/mm/dd'),
				},
				{
					title: '预计归还日',
					icon: '/image/orderDetail/back.png',
					description: uni.$uv.date(result, 'yyyy/mm/dd'),
				}
			]
		};
		const setTimestamp = timestamp => {
			if (timestamp) {
				var length = timestamp?.toString()?.length; // 获取时间戳位数
				if (length == 10) {
					return timestamp * 1000; // 秒级时间戳
				} else if (length == 13) {
					return timestamp; // 毫秒级时间戳
				}
			} else {
				return new Date().getTime(); // 未知类型
			}
		};
		setime(setTimestamp(time), month);
	}
	const filterCurrent = () => {
		return list.term_info.filter(p => p.status == 1)?.length - 1
	}
	const customStyle = (val) => {
		if (val == 1 || val == 4) {
			return {
				'color': '#999',
				'text-decoration': 'line-through',
				'font-size': '13px !important',
				'pointer-events': 'none'
			}
		} else if (val == 2 || val == 3) {
			return {
				'color': 'red',
				'font-size': '14px !important'
			}
		} else {
			return {
				'color': 'orange',
				'font-size': '14px !important'
			}
		}
	}
	const payMonthPay = (value) => {
		console.log(value.status,list.status ,'大大')
		if (value.status != 0 && !(list.value.status == 4 || list.value.status == 5 || list.value.status == 6 || list.value.status == 7)) {
			showToast("当前状态不可支付")
			return false;
		}
		app.vibrate()
		uni.showModal({
			title: "友情提示",
			content: "您确定要提前支付" + value.key + "租金吗?",
			confirmText: "去支付",
			success: (res) => {
				if (res.confirm) {
					// #ifdef H5
					let price = app.removeCurrencySymbolAndConvertToNumber(value.value)
					showPreview(value.expact, price);
					// #endif

					// #ifdef MP-WEIXIN
					onTestPay(value.expact)
					// #endif

				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const callPhone = () => {
		app.vibrate()
		uni.makePhoneCall({
			phoneNumber: miniprogram_info.value.miniprogram_phone,
			success: () => {

			},
			fail: () => {

			}
		});
	}
</script>

<style lang="scss" scoped>
	.testPay {
		background: red;
		color: #fff;
		text-align: center;
		line-height: 100rpx;
		width: 100%;
	}

	.cardBox {
		display: flex;
		flex-direction: column;
		gap: 10px;
	}

	.cardTitle {
		width: 100%;
		font-size: medium;
		font-weight: 600;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.cardExtra {
			color: #999;
			font-size: 12px;
		}
	}

	::v-deep {
		.uv-textarea {
			border-radius: 10px;
		}

		.uv-textarea--disabled {
			background-color: white !important;
		}

		.uv-steps-item {
			padding-bottom: 20px !important;

			.uv-steps-item__line {
				height: 50px !important;
				background-color: black !important;
			}

			.uv-steps-item__wrapper__dot {
				width: 8px !important;
				height: 8px !important;
				border: 3px solid black;
			}

			.uv-text__value {
				color: inherit !important;
				font-size: inherit !important;
			}

			.uv-steps-item__content--column {
				flex-direction: row !important;
				justify-content: space-between;
				margin-left: 10px !important;

				.uv-text {
					width: auto !important;
					flex: none !important;
				}
			}
		}
	}

	.line {
		box-shadow: 0 0.4px 0 rgba(18, 22, 33, .12);
	}

	.disable {
		pointer-events: none;
	}

	.ova {
		overflow-y: auto;
	}

	.h-30 {
		height: 30px;
	}

	.h-65 {
		height: 65px;
	}

	.card {
		background-color: white;
		padding: 10px;
		box-shadow: var(--nut-cell-box-shadow, 0 1px 7px 0 #edeef1);
		display: flex;
		flex-direction: column;
		justify-content: center;

		::v-deep {
			.uv-list-item__extra-text {
				color: red;
				font-weight: 600;
			}

			.nut-icon {
				display: block !important;
			}
		}
	}

	.nut-cell {
		padding: 10px !important;
	}

	.zujin {
		::v-deep {

			.uv-list-item__content,
			.uv-list-item__content-title,
			.uv-list-item__extra-text {
				color: inherit;
			}
		}
	}

	.p-2 {
		padding: 2px;
	}

	.p-10 {
		padding: 10px;
	}

	.p-0 {
		padding: 0 10px !important;
	}

	.f-14 {
		font-size: 14px;
	}

	.pd-0 {
		padding-bottom: 0;
	}

	.h-80 {
		height: 80px;
	}

	.flex {
		gap: 10px;
		width: 100%;
	}

	.cover {
		background-size: cover;
	}

	.center {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.active:active {
		transform: scale(0.98);
	}

	.f-15 {
		font-size: 15px;
	}

	.f-16 {
		font-size: 16px;
	}

	.align-center {
		display: flex;
		align-items: center;
	}

	.bold {
		font-weight: bold;
	}

	.between {
		justify-content: space-between;
	}

	.grow {
		flex-grow: 1;
	}

	.left {
		width: 30%;
		height: 100%;
	}

	.right {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: space-evenly;
	}

	.g-7 {
		gap: 7px;
	}

	.g-10 {
		gap: 10px;
	}

	.h-30 {
		height: 30px;
	}

	.h-100 {
		height: 100px;
	}

	.end {
		place-self: flex-end;
	}

	.ant-grid {
		width: 100%;
	}

	.ant-button {
		width: 100%;
		border-radius: 30px;
	}

	.ant-container {
		margin-bottom: 0;
	}

	::v-deep.uv-radio-group {
		flex: none !important;
	}

	.round {
		border-radius: 50px;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
		color: black;
	}

	.weight {
		font-weight: 700;
		font-size: 16px;
	}

	.size {
		font-size: small;
		-webkit-line-clamp: 3;
	}

	.status {
		color: orange;
		font-weight: blod;
	}

	.fontLong {
		-webkit-box-orient: vertical;
		display: -webkit-box;
		word-break: break-all;
	}

	.ant-tabs-content {
		margin: 10px;
		border-radius: 10px;
	}

	.yajin {
		width: 120px;
		text-align: center;
		background-color: #f5f5f5;
	}

	.ant-list-item {
		font-size: 10px;
	}

	.ant-list-item-line {
		padding: 5px;
	}

	.bottom {
		width: -webkit-fill-available;
		padding: 10px;
		gap: 10px;
		display: flex;
		flex-direction: column;
		padding-bottom: env(safe-area-inset-bottom);
		background-color: whitesmoke;
		box-shadow: var(--nut-cell-box-shadow, 0 0 10px rgb(237, 238, 241));
		backdrop-filter: blur(10px);
	}

	.wobble-hor-bottom {
		-webkit-animation: wobble-hor-bottom .8s infinite both;
		animation: wobble-hor-bottom .8s infinite both
	}

	@-webkit-keyframes wobble-hor-bottom {

		0%,
		100% {
			-webkit-transform: translateX(0);
			transform: translateX(0);
			-webkit-transform-origin: 50% 50%;
			transform-origin: 50% 50%
		}

		15% {
			-webkit-transform: translateX(-30px) rotate(-6deg);
			transform: translateX(-30px) rotate(-6deg)
		}

		30% {
			-webkit-transform: translateX(15px) rotate(6deg);
			transform: translateX(15px) rotate(6deg)
		}

		45% {
			-webkit-transform: translateX(-15px) rotate(-3.6deg);
			transform: translateX(-15px) rotate(-3.6deg)
		}

		60% {
			-webkit-transform: translateX(9px) rotate(2.4deg);
			transform: translateX(9px) rotate(2.4deg)
		}

		75% {
			-webkit-transform: translateX(-6px) rotate(-1.2deg);
			transform: translateX(-6px) rotate(-1.2deg)
		}
	}

	@keyframes wobble-hor-bottom {

		0%,
		100% {
			-webkit-transform: translateX(0);
			transform: translateX(0);
			-webkit-transform-origin: 50% 50%;
			transform-origin: 50% 50%
		}

		15% {
			-webkit-transform: translateX(-30px) rotate(-6deg);
			transform: translateX(-30px) rotate(-6deg)
		}

		30% {
			-webkit-transform: translateX(15px) rotate(6deg);
			transform: translateX(15px) rotate(6deg)
		}

		45% {
			-webkit-transform: translateX(-15px) rotate(-3.6deg);
			transform: translateX(-15px) rotate(-3.6deg)
		}

		60% {
			-webkit-transform: translateX(9px) rotate(2.4deg);
			transform: translateX(9px) rotate(2.4deg)
		}

		75% {
			-webkit-transform: translateX(-6px) rotate(-1.2deg);
			transform: translateX(-6px) rotate(-1.2deg)
		}
	}
</style>